﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ExpenseSystem.Model;
using ExpenseSystem.Fether;
using ExpenseSystem.DataUpdater;
using ExpenseSystem.Common;
using ExpenseSystem.Core.Authority;
using ExpenseSystem.DataUpdater.Validation;

namespace ExpenseSystem.Core.TitleModules
{
    public class TitleUpdaterRegister
    {
        int rows;
        public NormalDataUpdater<TitleModel> GetTitleUpdater()
        {
            NormalDataUpdater<TitleModel> systemDataUpdater = new NormalDataUpdater<TitleModel>();
            systemDataUpdater.DataUpdating += DataNotSpaceValid;
            systemDataUpdater.DataUpdating += SingletonValid;
            systemDataUpdater.DataDeleting += CheckFromEmployee;
            return systemDataUpdater;
        }

        private void CheckFromEmployee(object sender, DataValidationEventArgs<TitleModel> e)
        {
            EmployeeFetcher employeeFetcher = new EmployeeFetcher();
            string message;
            if( employeeFetcher.ListEmployeeByTitle(e.Delete.Site, e.Delete.AutoId,out message, out rows).Count!=0)
            {
                e.Cancle = true;
                message = "该信息已被使用";
            }
        }

        private void SingletonValid(object sender, DataValidationEventArgs<TitleModel> e)
        {
            TitleFetcher titleFetcher = new TitleFetcher();
            string message = "";
            TitleModel title = titleFetcher.GetByCode(Authority.Authority.GetUserProfile().SiteId, e.Insert.Code, out message);
            if (title != null && title.AutoId != e.Insert.AutoId)
            {
                e.Cancle = true;
                message = String.Format("代号[{0}]已被[{1}]占用", title.Code, title.Name);
                return;
            }
        }

        private void DataNotSpaceValid(object sender, DataValidationEventArgs<TitleModel> e)
        {
            if (String.IsNullOrWhiteSpace(e.Insert.Code))
            {
                e.Message = "代号不能为空";
                e.Cancle = true;
                return;
            }
            if (String.IsNullOrWhiteSpace(e.Insert.Name))
            {
                e.Message = "名称不能为空";
                e.Cancle = true;
                return;
            }
        }
    }
}
